<template>
  <a-card :bordered="false">
    <div class="table-operator">
      <!-- <a-button type="primary" icon="plus" @click="addGetList()">客户备案</a-button> -->
      <a-button icon="redo" type="primary" @click="getDataList()">刷新</a-button>
      <a-radio-group
        v-model="queryParam[1].keyword"
        :default-value="0"
        button-style="solid"
        style="margin-left: 8px"
        @change="userChange"
      >
        <a-radio-button :value="null"> 全部</a-radio-button>
        <a-radio-button :value="-1"> 备案中客户</a-radio-button>
        <a-radio-button :value="0"> 潜在客户</a-radio-button>
        <a-radio-button :value="1"> 正式客户</a-radio-button>
        <a-radio-button :value="2"> 休眠客户</a-radio-button>
        <a-radio-button :value="3"> 待转正客户</a-radio-button>
      </a-radio-group>
    </div>
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-input v-model="queryParam[0].keyword" allowClear placeholder="客户名称" @keydown="inputKeyDown"/>
            </a-form-item>
          </a-col>
          <a-col v-if="groupList.length > 1" :md="4" :sm="24">
            <a-select v-model="queryParam[2].keyword" placeholder="请选择分组" style="width: 100%">
              <a-select-option v-for="item in groupList" :key="item.GroupId" :value="item.GroupName">
                {{ item.GroupName }}
              </a-select-option>
            </a-select>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-button
              type="primary"
              @click="
                () => {
                  this.pagination.current = 1
                  this.getDataList()
                }">查询
            </a-button>
            <a-button style="margin-left: 8px" @click="Repossess1">重置</a-button>
          </a-col>
          <div class="right">
            <a-button
              :disabled="!hasSelected()"
              style="margin-left: 8px"
              type="primary"
              @click="btnOffer"
            >报价管理
            </a-button>
            <a-button
              :disabled="!hasSelected()"
              style="margin-left: 8px"
              type="primary"
              @click="OfferLook"
            >查看报价
            </a-button>
            <a-button
              :disabled="!hasSelected()"
              style="margin-left: 8px"
              type="primary"
              @click="btnSample"
            >样品管理
            </a-button>
            <!-- <a-button :disabled="!hasSelected()" style="margin-left: 8px" type="primary" @click="SampleLook"
              >查看样品</a-button
            > -->
          </div>
          <!-- <a-dropdown :disabled="!hasSelected()">
            <a-menu slot="overlay">
              <a-menu-item key="2" @click="btnOffer">报价管理</a-menu-item>
              <a-menu-item key="1" @click="OfferLook">查看报价</a-menu-item>
            </a-menu>
            <a-button type="primary" style="margin-right: 8px" large> 报价 <a-icon type="down" /> </a-button>
          </a-dropdown>

          <a-dropdown :disabled="!hasSelected()">
            <a-menu slot="overlay">
              <a-menu-item key="2" @click="btnSample">样品管理</a-menu-item>
              <a-menu-item key="1" @click="SampleLook">查看样品</a-menu-item>
            </a-menu>
            <a-button type="primary" style="margin-right: 8px" large> 样品 <a-icon type="down" /> </a-button>
          </a-dropdown> -->
        </a-row>
      </a-form>
    </div>

    <a-table
      ref="table"
      :bordered="true"
      :columns="columns"
      :customRow="loadCustomRow"
      :dataSource="data"
      :loading="loading"
      :pagination="pagination"
      :rowKey="(row, index) => row.Id"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'radio' }"
      :scroll="{ y: tableHeight }"
      size="small"
      @change="handleTableChange">
      <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span>
      <template slot="cCusType" slot-scope="text, record">
        <a-tag v-if="record.cCusType === 0" color="blue">潜在</a-tag>
        <a-tag v-else-if="record.cCusType === 1" color="green">正式</a-tag>
        <a-tag v-else-if="record.cCusType === 2" color="red">休眠</a-tag>
        <a-tag v-else-if="record.cCusType === 3" color="orange">待转正</a-tag>
      </template>
      <template slot="GroupStatus" slot-scope="text, record">
        <a-tag v-if="record.GroupStatus === 0" color="blue">未分组</a-tag>
        <a-tag v-else-if="record.GroupStatus === 1" color="orange">申请中</a-tag>
        <a-tag v-else-if="record.GroupStatus === 2" color="green">已分组</a-tag>
      </template>
      <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a v-if="hasPerm('Cust_CustomerApply.Del')" @click="Detail(record)">详情</a>
          <a-divider v-if="hasPerm('Cust_CustomerApply.Del')" type="vertical"/>
          <a v-if="hasPerm('Cust_CustomerApply.edit')" @click="handleEdit(record.Id)">编辑</a>
          <a-divider v-if="hasPerm('Cust_CustomerApply.edit')" type="vertical"/>
          <a v-if="hasPerm('SalesmanDailyRecord.Edit')" @click="communication(record.Id, record.cCusName)">沟通</a>
          <a-divider v-if="record.cCusType === 0" type="vertical"/>
          <a v-if="record.cCusType === 0" @click="application(record)">转正申请</a>
          <a-divider v-if="record.cCusType === 0" type="vertical"/>
          <a v-if="record.cCusType === 0" @click="dele(record.Id)">删除</a>
          <!--<a-divider v-if="hasPerm('ar_baddebts.Enter')" type="vertical"/>-->
          <!--<a v-if="hasPerm('ar_baddebts.Enter')" @click="OpenAr_baddebts(record)">坏账</a>-->
        </template>
      </span>
    </a-table>
    <edit-form ref="editForm" :parentObj="this"></edit-form>
    <UserOffer ref="useroffer" :parentObj="this"></UserOffer>
    <Myoffer ref="Myoffer"/>
    <UserShip ref="usership" :parentObj="this"></UserShip>
    <MyShip ref="MyShip"/>
    <UserSample ref="usersample" :parentObj="this"></UserSample>
    <!-- <MySample ref="MySample" /> -->
    <UserGift ref="usergift" :parentObj="this"></UserGift>
    <CustLink ref="custLink" :parentObj="this"></CustLink>
    <CusEditForm ref="details" :parentObj="this"></CusEditForm>
    <Detailsfrom ref="detailsfrom" :parentObj="this"></Detailsfrom>
    <PotentialDetail ref="PotentialDetail" :parentObj="this"></PotentialDetail>
    <CommunicationForm ref="communicationForm" :parentObj="this"/>
    <ArEditForm ref="ArEditForm" :parentObj="this"></ArEditForm>
  </a-card>
</template>

<script>
import OperatorCache from '@/utils/cache/OperatorCache'
import CommunicationForm from './CommunicationForm.vue' // 沟通记录
import EditForm from './EditForm.vue'
import UserOffer from './UserOffer.vue'
import Myoffer from './Information/Myoffer.vue'
import MyShip from './Information/MyShip.vue'
import UserShip from './UserShip.vue'
import UserSample from '../../SampleManagement/MySample/EditForm.vue'
import UserGift from './UserGift.vue'
import CustLink from '../Cust_CustomerLinkMan/List.vue'
import CusEditForm from '../Customer/EditForm.vue'
import PotentialDetail from '../Cust_CustomerInfoPotential/EditForm.vue'
import Detailsfrom from '@/views/CustomerManagement/Customer/Details.vue'
import ArEditForm from '@/views/CustomerManagement/ar_baddebts/EditForm.vue'
import moment from 'moment'
// import MySample from './Information/MySample.vue'

const columns = [
  { title: '客户编码', dataIndex: 'cCusCode', align: 'center', width: '10%' },
  { title: '客户名称', dataIndex: 'cCusName', align: 'left' },
  { title: '创建时间', dataIndex: 'CreateTime', width: '10%', scopedSlots: { customRender: 'CreateTime' } },
  { title: '客户分组', dataIndex: 'GroupName', width: '10%', align: 'center' },
  { title: '业务负责人', dataIndex: 'PrincipalName', width: '10%', align: 'center' },
  { title: '客户类型', dataIndex: 'cCusType', align: 'center', width: '5%', scopedSlots: { customRender: 'cCusType' } },
  // {
  //   title: '分组状态',
  //   dataIndex: 'GroupStatus',
  //   align: 'center',
  //   width: '100px',
  //   // customRender: (value) => {
  //   //   if (value == 0) return '潜在'
  //   //   if (value == 1) return '正式'
  //   //   if (value == 2) return '休眠'
  //   // },
  //   scopedSlots: { customRender: 'GroupStatus' }
  // },
  { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' }, width: '280px' }
]

export default {
  components: {
    CommunicationForm,
    EditForm,
    UserOffer,
    Myoffer,
    UserShip,
    MyShip,
    UserSample,
    // MySample,
    UserGift,
    CustLink,
    CusEditForm,
    PotentialDetail,
    Detailsfrom,
    ArEditForm
  },
  mounted () {
    this.$nextTick(() => {
      // 页面渲染完成后的回调
      this.tableHeight = this.getTableHeight(true) + 24.5
    })
    this.getlist()
    this.getDataList()
    this.getGroupList()
  },
  data () {
    return {
      tableHeight: 570, // 表格高度
      state: null,
      columns,
      selectedRows: [],
      user: 1,
      data: [],
      groupList: [],
      list: [], // 省级
      listChildren: [], // 市
      county: [], // 县
      total: 0,
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      filters: {},
      sorter: { field: 'CreateTime', order: 'desc' },
      loading: false,
      Id: '',
      queryParam: [{ condition: 'cCusName' }, { condition: 'cCusType', keyword: null }, { condition: 'GroupName' }],
      selectedRowKeys: []
    }
  },
  methods: {
    getGroupList () {
      this.$http
        .post('/CustomerManagement/Cust_GroupAllocationOfUser/GetDataList', {
          Search: {
            Condition: 'SalesmanId',
            Keyword: this.op().Id
          }
        })
        .then(res => {
          this.groupList = res.Data
          console.log(this.groupList)
        })
    },
    op () {
      return OperatorCache.info
    },
    inputKeyDown (e) {
      if (e.keyCode === 13) {
        if (!this.queryParam[0].keyword) return this.$message.error('请输入查询条件')
        this.getDataList()
      }
    },
    application (record) {
      this.$confirm({
        title: '确认提交转正申请吗?',
        onOk: () => {
          let obj = {}
          obj = record
          obj.CustomerId = record.Id
          obj.CustomerName = record.cCusName
          obj.Id = null
          obj.SalesmanId = this.op().Id
          obj.SalesmanName = this.op().RealName
          obj.ApprovalStatus = record.cCusType
          obj.ApplyDate = record.CreateTime
          obj.Type = '1'
          this.$http.post('/CustomerManagement/Cust_CustomerApply/SaveData', obj).then(resJson => {
            if (resJson.Success) {
              this.$message.success('转正申请提交成功!')
              this.getDataList()
            } else {
              this.$message.error(resJson.Msg)
            }
          })
        }
      })
    },
    communication (Id, name) {
      this.$refs.communicationForm.openForm(Id + '_' + name)
    },
    // 客户备案
    addGetList () {
      this.$refs.detailsfrom.openForm(null, '添加')
    },
    OfferLook () {
      this.$refs.Myoffer.openForm(this.selectedRows[0].cCusName)
    },
    SampleLook () {
      this.$refs.MySample.openForm(this.selectedRows[0].cCusName)
    },
    ShipLook () {
      this.$refs.MyShip.openForm(this.selectedRows[0].cCusName)
    },

    handleMenuClick (id, e) {
    },
    // 省市区的模糊查询
    filterOption (input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    showSizeChange (page, pageSize) {
      this.pagination.current = page
      this.pagination.pageSize = pageSize

      this.getDataList()
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }

      this.getDataList()
    },
    CustomerLinkMan (customer) {
      this.$refs.custLink.openForm(customer, '客户联系人')
    },
    Repossess1 () {
      this.queryParam = [
        { condition: 'cCusName' },
        { condition: 'cCusType', keyword: null },
        { condition: 'GroupName' }
      ]
    },

    Detail (Id) {
      this.$refs.details.openForm(Id, '详情', true)
    },
    // 潜在客户详情
    PotentialDetail (Id) {
      this.$refs.PotentialDetail.openForm(Id, '详情')
    },
    // 报价
    btnOffer (item) {
      this.$refs.useroffer.openForm(this.selectedRows[0], '客户报价')
    },
    // 发货
    btnShip (item) {
      this.$refs.usership.openForm(this.selectedRows[0], '客户发货')
    },
    // 样品管理
    btnSample (item) {
      this.$refs.usersample.openForm(null, '客户样品', this.selectedRows[0])
    },
    // 返料
    btnGift (item) {
      this.$refs.usergift.openForm(item, '客户返料')
    },
    Distribute (row) {
      this.$refs.editForm.openForm(row, '分配客户')
    },
    userChange (n) {
      this.getDataList()
    },
    // 市级change
    city (e) {
      this.$http.post('/Base_BasicData/Base_District/GetDataListByPId?pId=' + e, {}).then(resJson => {
        this.loading = false
        this.listChildren = resJson.Data
        delete this.queryParam[2].keyword
        delete this.queryParam[3].keyword
      })
    },

    // 县change
    village (e) {
      this.$http.post('/Base_BasicData/Base_District/GetDataListByPId?pId=' + e, {}).then(resJson => {
        this.loading = false
        this.county = resJson.Data
      })
    },
    // 获取省份信息
    getlist (e) {
      this.$http.post('/Base_BasicData/Base_District/GetDataListByPId?pId=0', {}).then(resJson => {
        this.loading = false
        this.list = resJson.Data
      })
    },
    getDataList () {
      this.selectedRowKeys = []
      this.loading = true
      this.$http
        .post('/CustomerManagement/CustomerInfo/GetDataListByMySelfAndMoreCondition', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          Search: this.queryParam,
          ...this.filters
        })
        .then(resJson => {
          if (resJson.Success) {
            this.data = resJson.Data
            if (this.data) {
              const pagination = { ...this.pagination }
              pagination.total = resJson.Total
              this.pagination = pagination
            }
            this.loading = false
          }
        })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    hasSelected () {
      return this.selectedRowKeys.length > 0
    },
    contactPerson (row) {
      this.$refs.List.openForm(row, '客户联系人')
    },
    handleAdd () {
      this.$refs.editForm.openForm(null, '新建正式客户信息表信息')
    },
    handleEdit (id) {
      this.$refs.detailsfrom.openForm(id, '编辑信息')
    },
    dele (ids) {
      const thisObj = this
      this.$confirm({
        title: '客户信息删除会解除与分组关系,确定删除吗?',
        onOk () {
          return new Promise((resolve, reject) => {
            thisObj.$http.post('/CustomerManagement/CustomerInfo/DeleteDataByCustomerId', { id: ids }).then(resJson => {
              resolve()

              if (resJson.Success) {
                thisObj.$message.success('操作成功!')

                thisObj.getDataList()
              } else {
                thisObj.$message.error(resJson.Msg)
              }
            })
          })
        }
      })
    },
    OpenAr_baddebts (record) {
      this.$refs.ArEditForm.openForm(record, '编辑坏账信息')
    },
    loadCustomRow (record, index) {
      return {
        on: {
          click: () => {
            // 记录为disabled则直接返回，默认为不可选
            if (record.disabled) return
            const type = 'radio'
            const key = record.Id || index
            let selectedRows = this.selectedRows
            let selectedRowKeys = this.selectedRowKeys
            if (type === 'radio') {
              selectedRowKeys = [key]
              selectedRows = [record]
            }
            if (!this.selectedRowKeys.includes(key)) {
              selectedRowKeys.push(key)
              selectedRows.push(record)
            } else {
              const index = this.selectedRowKeys.findIndex(skey => skey === key)
              selectedRows.splice(index, 1)
              selectedRowKeys.splice(index, 1)
            }

            this.updateSelect(selectedRowKeys, selectedRows)
            this.onSelectChange(selectedRowKeys, selectedRows)
          }
        }
      }
    },
    updateSelect (selectedRowKeys, selectedRows) {
      this.selectedRows = selectedRows
      this.selectedRowKeys = selectedRowKeys
    },
    timeFormat (val) {
      // 时间格式化函数
      return moment(val).format('YYYY-MM-DD HH:mm')
    }
  }
}
</script>

<style lang="less" scoped>
img {
  padding: 2px;
}

.pagination {
  float: right;
}

// 设定板块高度  内置滚动条
.customerBox {
  display: flex;
  flex-wrap: wrap;
  overflow: auto;
  height: 640px;
}

.customerCard {
  width: 300px;
  height: 190px;
  margin: 10px;
  text-align: center;
  position: relative;
  background-color: #f0f2f5;
  border-radius: 10px 10px 0 0;
}

/deep/ .ant-card-actions {
  width: 100%;
  position: absolute;
  bottom: 0;
}

.right {
  float: right;
}
</style>
